package xkp.lesson5;

public class TestWaitNotify {
    public static void main(String[] args) throws InterruptedException {
       Object object = new Object();
       MyWaitThread waitThread1 = new MyWaitThread(object);
       MyWaitThread waitThread2 = new MyWaitThread(object);
       MyWaitThread waitThread3 = new MyWaitThread(object);
       waitThread1.start();
       waitThread2.start();
       waitThread3.start();
       Thread.sleep(3000);

       synchronized (object){
           object.notifyAll();
       }
      /* MyNotifyThread notifyThread = new MyNotifyThread(object);
       notifyThread.start();*/
    }
}

class MyWaitThread extends Thread{
    private Object object;
    public MyWaitThread(Object object){
        this.object = object;
    }

    @Override
    public void run() {
        System.out.println("线程开始等待...");
        try {
            synchronized (object) {
                //wait方法只能在同步代码块中使用
                object.wait();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("线程被唤醒");
    }
}


class MyNotifyThread extends Thread{
    private Object object;
    public MyNotifyThread(Object object){
        this.object = object;
    }

    @Override
    public void run() {
        System.out.println("唤醒所有在obj上等待的线程....");
        synchronized (object){
            object.notifyAll();
        }
    }
}
